<?php
    $DEBUG = false;
    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    if (!isLoggedIn()) {
        exit();
    }
    
    if ($_SESSION['User']->UserType != "Manager" && $_SESSION['User']->UserType != "Representative") { //Invalid privileges!
        exit();
    }
    
    if (!isset($_POST["op"])) {
        exit();
    }
    
    $arr = array();
    $arr["Success"] = 0;
    include_once "db/db_cse305.php";
    
    $op = $_POST["op"];
    
    if ($op == "create") {
        if (!isset($_POST["accid"]) || !isset($_POST["stocksym"]) || !isset($_POST["ordertype"]) || !isset($_POST["numshares"]) || !isset($_POST["fee"]) || !isset($_POST["pricetype"])) {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        
        if ($_POST["accid"] == "" || $_POST["stocksym"] == "" || $_POST["ordertype"] == "" || $_POST["numshares"] == "" || $_POST["fee"] == "" || $_POST["pricetype"] == "") {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        
        
        if (!is_numeric($_POST["accid"]) ||  !isAllNumbers($_POST["accid"])) {
            $arr["Msg"] = "Invalid accid.";
            echo json_encode($arr);
            exit();
        }
        
        $accid = $_POST["accid"];
        $stocksym = $_POST["stocksym"];
        $ordertype = $_POST["ordertype"];
        if ($ordertype != "sell" && $ordertype != "buy") {
            $arr["Msg"] = "Invalid order type.";
            echo json_encode($arr);
            exit();
        }
        
        $query = sprintf("SELECT * FROM accounts WHERE AccountID = %d", mysql_real_escape_string($accid));
        $result = mysql_query($query) or die(mysql_error());
        if ($row = mysql_fetch_array($result)) {
        } else {
            $arr["Msg"] = "Account does not exist.";
            echo json_encode($arr);
            exit();
        }
        
        $stockprice = "";
        $query = sprintf("SELECT * FROM stocks WHERE StockSymbol = '%s'", mysql_real_escape_string($stocksym));
        $result = mysql_query($query) or die(mysql_error());
        if ($row = mysql_fetch_array($result)) {
            $stockprice = $row["SharePrice"];
        } else {
            $arr["Msg"] = "Stock Symbol does not exist.";
            echo json_encode($arr);
            exit();
        }
        
        $numshares = $_POST["numshares"];
        $fee = $_POST["fee"];
        if (!is_numeric($numshares) || !isAllNumbers($numshares)) {
            $arr["Msg"] = "Invalid share number.";
            echo json_encode($arr);
            exit();
        }
        if (!is_numeric($fee) || !isAllNumbers($fee)) {
            $arr["Msg"] = "Invalid fee amount.";
            echo json_encode($arr);
            exit();
        }
        
        
        
        $query = "";
        $pricetype = $_POST["pricetype"];
        if ($pricetype == "market" || $pricetype == "close") {
            if ($pricetype == "market")
                $pricetype = $stockprice;
            mysql_query("LOCK TABLE orders, accountholdings WRITE");
            
            if ($ordertype == "sell") {
                $query = sprintf("SELECT * FROM accountholdings WHERE AccountID = %d && StockSymbol = '%s'", $accid, $stocksym);
                $result = mysql_query($query) or die(mysql_error());
                if ($row = mysql_fetch_array($result)) {
                    $actShares = $row["NumShares"];
                    if ($actShares < $numshares) {
                        $arr["Msg"] = "That customer doesn't have enough of " . $stocksym . " to sell!";
                        echo json_encode($arr);
                        mysql_query("UNLOCK TABLE");
                        exit();
                    } else if ($numshares == $actShares) {
                        mysql_query(sprintf("DELETE FROM accountholdings WHERE AccountID = %d && StockSymbol = '%s'", $accid, $stocksym));
                    } else if ($actShares > $numshares) {
                        $query = sprintf("UPDATE accountholdings SET `NumShares` = `NumShares` - %d WHERE `AccountID` = %d && `StockSymbol` = '%s'",
                                $numshares, $accid, $stocksym);
                        mysql_query($query);
                    }
                } else {
                    $arr["Msg"] = "That customer has none of " . $stocksym . " to sell!";
                    echo json_encode($arr);
                    mysql_query("UNLOCK TABLE");
                    exit();
                }
            }
            
            $query = "SELECT MAX(`OrderID`) + 1 AS `newid` FROM orders";
            $result = mysql_query($query) or die(mysql_error());
            $id = "";
            if ($row = mysql_fetch_array($result)) {
                $id = $row["newid"];
            }
            $query = sprintf("INSERT INTO orders (`OrderID`, `OrderType`, `StockSymbol`, `NumShares`, `AccountID`, `PriceType`, `Fee`, `EmployeeID`) VALUES (%d, '%s', '%s', %d, %d, '%s', %d, %d)",
                        $id, $ordertype, $stocksym, $numshares, $accid, $pricetype, $fee, $_SESSION['User']->UserID
                    );
            $result = mysql_query($query) or die(mysql_error());
            if (mysql_affected_rows() > 0) {
                $arr["Success"] = 1;
                
                
                if ($ordertype == "buy") {
                    $query2 = sprintf("SELECT * FROM accountholdings WHERE AccountID = %d && StockSymbol = '%s'", $accid, $stocksym);
                    $result2 = mysql_query($query2) or die(mysql_error());
                    if ($row2 = mysql_fetch_array($result2)) {
                        $query3 = sprintf("UPDATE accountholdings SET `NumShares` = `NumShares` + %d WHERE `AccountID` = %d && `StockSymbol` = '%s'",
                            $numshares, $accid, $stocksym);
                    } else {
                        $query3 = sprintf("INSERT INTO accountholdings (`AccountID`, `StockSymbol`, `NumShares`,) VALUES (%d, '%s', %d)",
                            $accid, $stocksym, $numshares);
                    }
                    mysql_query($query3);
                }
                
                mysql_query("UNLOCK TABLE");
                echo json_encode($arr);
                exit();
            } else {
                $arr["Msg"] = "Something went wrong ...";
                echo json_encode($arr);
                mysql_query("UNLOCK TABLE");
                exit();
            }
        } else if ($pricetype == "trailing" || $pricetype == "hidden") {
            if ($pricetype == "hidden") {
                $pricetype = "hidden price";
            } else if ($pricetype == "trailing") {
                $pricetype = "trailing stop";
            }
            if (!isset($_POST["percent"]) || $_POST["percent"] == "") {
                $arr["Msg"] = "Invalid percentage.";
                echo json_encode($arr);
                exit();
            }
            $percent = $_POST["percent"];
            if (!is_numeric($percent) || !isAllNumbers($percent)) {
                $arr["Msg"] = "Invalid percentage.";
                echo json_encode($arr);
                exit();
            }
            
            mysql_query("LOCK TABLE orders WRITE");
            $query = "SELECT MAX(`OrderID`) + 1 AS `newid` FROM orders";
            $result = mysql_query($query) or die(mysql_error());
            $id = "";
            if ($row = mysql_fetch_array($result)) {
                $id = $row["newid"];
            }
            
            
            $query = sprintf("INSERT INTO orders (`OrderID`, `OrderType`, `StockSymbol`, `NumShares`, `AccountID`, `PriceType`, `Fee`, `Percentage`, `EmployeeID`) VALUES (%d, '%s', '%s', %d, %d, '%s', %d, %d, %d)",
                        $id, $ordertype, $stocksym, $numshares, $accid, $pricetype, $fee, $percent, $_SESSION['User']->UserID
                    );
            $result = mysql_query($query) or die(mysql_error());
            if (mysql_affected_rows() > 0) {
                $arr["Success"] = 1;
                if ($ordertype == "buy") {
                    $query2 = sprintf("SELECT * FROM accountholdings WHERE AccountID = %d && StockSymbol = '%s'", $accid, $stocksym);
                    $result2 = mysql_query($query2) or die(mysql_error());
                    if ($row2 = mysql_fetch_array($result2)) {
                        $query3 = sprintf("UPDATE accountholdings SET `NumShares` = `NumShares` + %d WHERE `AccountID` = %d && `StockSymbol` = '%s'",
                            $numshares, $accid, $stocksym);
                    } else {
                        $query3 = sprintf("INSERT INTO accountholdings (`AccountID`, `StockSymbol`, `NumShares`,) VALUES (%d, '%s', %d)",
                            $accid, $stocksym, $numshares);
                    }
                    mysql_query($query3);
                }
                echo json_encode($arr);
                mysql_query("UNLOCK TABLE");
                exit();
            } else {
                $arr["Msg"] = "Something went wrong ...";
                echo json_encode($arr);
                mysql_query("UNLOCK TABLE");
                exit();
            }
            
        } else {
            $arr["Msg"] = "Invalid price type";
            echo json_encode($arr);
            exit();
        }
    } else if ($op == "edit") {
        if (!isset($_POST["orderid"]) || !isset($_POST["numshares"]) || !isset($_POST["fee"])) {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        
        if ($_POST["orderid"] == "" || $_POST["numshares"] == "" || $_POST["fee"] == "") {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        
        $orderid = $_POST["orderid"];
        if (!is_numeric($orderid) || !isAllNumbers($orderid)) {
            $arr["Msg"] = "Invalid order id.";
            echo json_encode($arr);
            exit();
        }
        
        $numshares = $_POST["numshares"];
        if (!is_numeric($numshares) || !isAllNumbers($numshares)) {
            $arr["Msg"] = "Num shares missing.";
            echo json_encode($arr);
            exit();
        }
        
        $fee = $_POST["fee"];
        if (!is_numeric($fee) || !isAllNumbers($fee)) {
            $arr["Msg"] = "Fee missing.";
            echo json_encode($arr);
            exit();
        }
        
        $query = sprintf("SELECT * FROM orders WHERE OrderID = %d", mysql_real_escape_string($orderid));
        $result = mysql_query($query) or die(mysql_error());
        
        if ($row = mysql_fetch_array($result)) {
            $pricetype = $row["PriceType"];
            $ordertype = $row["OrderType"];
            $stocksym = $row["StockSymbol"];
            $accid = $row["AccountID"];
            $percent = $row["Percentage"];
        } else {
            $arr["Msg"] = "Order not found.";
            echo json_encode($arr);
            exit();
        }
        
        if ($pricetype != "trailing stop" && $pricetype != "hidden stop") {
            $arr["Msg"] = "You can only add transactions to trailing and hidden stops.";
            echo json_encode($arr);
            exit();
        }
        $query = sprintf("INSERT INTO orders (`OrderID`, `OrderType`, `StockSymbol`, `NumShares`, `AccountID`, `PriceType`, `Fee`, `Percentage`, `EmployeeID`) VALUES (%d, '%s', '%s', %d, %d, '%s', %d, %d, %d)",
                        $orderid, $ordertype, $stocksym, $numshares, $accid, $pricetype, $fee, $percent, $_SESSION['User']->UserID
                    );
        $result = mysql_query($query) or die(mysql_error());
        if (mysql_affected_rows() > 0) {
            $arr["Success"] = 1;
            echo json_encode($arr);
            exit();
        } else {
            $arr["Msg"] = "Something went wrong ...";
            echo json_encode($arr);
            exit();
        }
    } else {
        $arr["Msg"] = "Invalid operation.";
    }
    echo json_encode($arr);
    
    function isAllNumbers($v) {
        for ($i = 0;$i < strlen($v);$i++) {
            $t = is_numeric($v[$i]);
            if (!$t) return 0;
        }
        return 1;
    }
?>
